import os
import math
import yaml
from flask import (Flask, render_template, redirect, url_for, request, flash)
from flask.ext.bootstrap import Bootstrap
from flask.ext.moment import Moment
from werkzeug.utils import secure_filename
from datetime import datetime
from rookout.base import (list_dir, read_file)
from operator import itemgetter
from uploadForm import UploadForm

app = Flask(__name__)
app.config['BOOTSTRAP_SERVE_LOCAL'] = True
app.config['SECRET_KEY'] = "It is hard to guess."
bootstrap = Bootstrap(app)
moment = Moment(app)
workdir = os.path.split(os.path.abspath(__file__))[0]
config = yaml.load(read_file(os.path.join(workdir, 'config.yaml')))
links = yaml.load(read_file(os.path.join(workdir, 'links.yaml')))
project_list = config['project_list']
package_dir = config['package_dir']
ppt_dir = config['ppt_dir']

def edit_link(pos, section, name, href):
    links_file = yaml.load(read_file(os.path.join(workdir, 'links.yaml')))
    update_data = {'title': str(name), 'href': str(href)}
    for value in links_file['links']:
        if value['name'] == section:
            del value['list'][pos-1]
            value['list'].insert(pos-1, update_data)
            break
    print (links_file)
    return links_file

def new_link(section, name, href):
    links_file = yaml.load(read_file(os.path.join(workdir, 'links.yaml')))
    update_data = {'title': str(name), 'href': str(href)}
    for value in links_file['links']:
        if value['name'] == section:
            value['list'].insert(0, update_data)
            break
    print (links_file)
    return links_file

def delete_link(section, name, href):
    links_file = yaml.load(read_file(os.path.join(workdir, 'links.yaml')))
    for value in links_file['links']:
        if value['name'] == section:
            i = 0
            for list_item in value['list']:
                if list_item['href'] == href and list_item['title'] == name:
                    del value['list'][i]
                    print ("Done! " + list_item['href'] + list_item['title'])
                    break
                else: 
                    i = i + 1
    return links_file

def write_link_data(data):
    file_stream = open(os.path.join(workdir, 'links.yaml'),'w')
    links_file = yaml.dump(data,file_stream)
    file_stream.close()

def get_files(dir_path):
    files = []
    dirs = []
    for fname in list_dir(dir_path):
        path = os.path.join(dir_path, fname)
        if os.path.isdir(path):
            dirs.append({
                "name":fname
                })
        else:
            stat = os. stat(path)
            files.append({
                "name":fname,
                "size":stat.st_size,
                "time":datetime.fromtimestamp(math.floor(stat.st_ctime))
                })
    files.sort(key=itemgetter('time'), reverse=True)
    return files, dirs

@app.route('/')
def index():
    return render_template('index.html',
            current_time=datetime.utcnow(),
            links=links['links'],dirs=project_list
            )

@app.route('/user/<name>')
def user(name):
    return render_template('user.html', name=name)

@app.route('/package/')
def package():
    files, dirs = get_files(config['package_dir'])
    return render_template('package.html', files=files, dirs=project_list)

@app.route('/package/<project>/')
def package_project(project):
    dir_path = os.path.join(config['package_dir'], project)
    if not os.path.exists(dir_path):
        return 404
    files, dirs = get_files(dir_path)
    return render_template('package.html', files=files, project=project, dirs=project_list)

@app.route('/package/<project>/<prosub>/')
def package_prosub(project, prosub):
    dir_path = os.path.join(config['package_dir'], project, prosub)
    if not os.path.exists(dir_path):
        return 404
    # 丢弃 dir 信息
    files, dirs = get_files(dir_path)
    return render_template('package.html', files=files, project=project, prosub=prosub,dirs=project_list)

# 文件上传
@app.route('/ppt/upload',methods=["GET","POST"])
def upload():
    secDir_path = ""
    form = UploadForm()
    files, dirs = get_files(config['package_dir'])
    if form.validate_on_submit():
        levelOneDir = form.levelone_Dir.data
        secLevelDir = form.secLevel_Dir.data
        uploadFileName = secure_filename(form.file_name.data.filename)
        if len(secLevelDir) == 0:
            uploadFileFullPath = os.path.join(ppt_dir,levelOneDir, uploadFileName)
        else:
            secDir_path = os.path.join(ppt_dir,levelOneDir,secLevelDir)
            uploadFileFullPath = os.path.join(secDir_path, uploadFileName)
        print (uploadFileFullPath)
        if os.path.exists(uploadFileFullPath):
            flash('File %s already exists!' %uploadFileFullPath)
        else:
            if len(secDir_path) != 0:
                os.mkdir(secDir_path)
            form.file_name.data.save(uploadFileFullPath)
            download_path = os.path.join(levelOneDir, secLevelDir,uploadFileName)
            flash('File %s is uploaded sucessfully!' %uploadFileFullPath)
            flash('Download path: http://game.baina.com/ppt/%s' %download_path)
    return render_template('upload.html', files=files, dirs=project_list,form=form)

# pacakge删除
@app.route('/delete', methods=["POST"])
def delete_files():
    data = request.form.getlist('fileList[]')
    for fname in data:
        path = os.path.join(package_dir,fname)
        print (path)
        if os.path.exists(path):
            os.remove(path)
            print ("Done")
    return redirect("/")

# admin页面
@app.route('/management/admin',methods=["GET","POST"])
def manage_linkpage():
    files, dirs = get_files(config['package_dir'])
    link_list = yaml.load(read_file(os.path.join(workdir, 'links.yaml')))
    return render_template('linkpage.html', links=link_list['links'],dirs=project_list)

@app.route('/management/admin/delete',methods=["GET","POST"])
def delete_linkpage():
    files, dirs = get_files(config['package_dir'])
    link_list = yaml.load(read_file(os.path.join(workdir, 'links.yaml')))
    section = request.form.getlist('section')
    name = request.form.getlist('link')
    href = request.form.getlist('href')
    data = delete_link(''.join(section),''.join(name), ''.join(href))
    write_link_data(data)
    return render_template('linkpage.html', links=link_list['links'],dirs=project_list)

@app.route('/management/admin/edit',methods=["GET","POST"])
def edit_linkpage():
    files, dirs = get_files(config['package_dir'])
    link_list = yaml.load(read_file(os.path.join(workdir, 'links.yaml')))
    name = request.form.getlist('link')
    href = request.form.getlist('href')
    section = request.form.getlist('section')
    pos = request.form.getlist('pos')
    print (pos,name,href,section)
    data = edit_link(int(''.join(pos)),''.join(section),''.join(name), ''.join(href))
    write_link_data(data)
    return render_template('linkpage.html', links=link_list['links'],dirs=project_list)

@app.route('/management/admin/new',methods=["GET","POST"])
def new_linkpage():
    files, dirs = get_files(config['package_dir'])
    link_list = yaml.load(read_file(os.path.join(workdir, 'links.yaml')))
    name = request.form.getlist('link')
    href = request.form.getlist('href')
    section = request.form.getlist('section')
    print (name,href,section)
    data = new_link(''.join(section),''.join(name), ''.join(href))
    write_link_data(data)
    return render_template('linkpage.html', links=link_list['links'],dirs=project_list)

@app.errorhandler(404)
def page_not_found(e):
    return render_template('404.html'), 404

if __name__ == "__main__":
    app.run(host="0.0.0.0",debug=True)
